/*
 * websocket client
 *
 * @build   make examples
 * @server  bin/websocket_server_test 8888
 * @client  bin/websocket_client_test ws://127.0.0.1:8888/
 * @js      html/websocket_client.html
 *
 */

#include "web_service.hpp"

#include "spdlog/spdlog.h"

WebSocketService::WebSocketService() { SPDLOG_TRACE("Constructed."); }

WebSocketService::WebSocketService(const char* url) {
  Init(url);
  SPDLOG_TRACE("Constructed.");
}

WebSocketService::~WebSocketService() { SPDLOG_TRACE("Destructed."); }

void WebSocketService::Init(const char* url) {
  reconn_setting_t reconn;
  reconn_setting_init(&reconn);
  reconn.min_delay = 1000;
  reconn.max_delay = 10000;
  reconn.delay_policy = 2;
  ws.setReconnect(&reconn);

  http_headers headers;
  headers["Origin"] = "http://robots.iff.qdu.edu.cn/";
  headers["User-agent"] = "Iff-robot";
  ws.open(url, headers);
  SPDLOG_INFO("Web service opend at {}", url);

  ws.onopen = []() { SPDLOG_DEBUG("Opened."); };
}

void WebSocketService::SendMessage(const char* message) {
  if (ws.isConnected()) {
    ws.send(message);
  };
}

void WebSocketService::onMessage(void (*callback)(const char* msg),
                                 const char* msg) {
  callback(msg);
}
